package com.leyou.item.service;


import com.leyou.common.utils.RequestHolder;
import com.leyou.item.dao.AclMapper;
import com.leyou.item.dao.RoleAclMapper;
import com.leyou.item.dao.RoleUserMapper;
import com.leyou.item.pojo.*;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

/**
 * @author:yanjizhw@163.com
 * @date:2019-10-15 13:12
 * 描述:
 * @since:1.0.0
 */
@Service
public class CoreService {

    @Autowired
    private AclMapper aclMapper;

    @Autowired
    private RoleUserMapper roleUserMapper;

    @Autowired
    private RoleAclMapper roleAclMapper;

    public List<Acl> getCurrentUserAclList() {

        Manager user = (Manager) RequestHolder.getCurrentUser();
        int userId = user.getId();

        return getUserAclList(userId);
    }

    private List<Acl> getUserAclList(int userId) {
        if (isSuperAdmin()){
            return aclMapper.selectAll();
        }
        Example ex1 = new Example(RoleUser.class);
        ex1.createCriteria().andEqualTo("user_id", userId);
        List<RoleUser> roleUsers = roleUserMapper.selectByExample(ex1);
        if (CollectionUtils.isEmpty(roleUsers)) {
            return new ArrayList();
        }
        Example ex2 = new Example(RoleAcl.class);
        ex2.createCriteria().andEqualTo("role_id", roleUsers.get(0).getRole_id());
        List<RoleAcl> roleAcls = roleAclMapper.selectByExample(ex2);
        if (CollectionUtils.isEmpty(roleAcls)) {
            return new ArrayList();
        }

        List<Integer> idList = new ArrayList();
        for (RoleAcl roleAcl: roleAcls){
            idList.add(roleAcl.getRole_id());
        }
        return aclMapper.getByIdList(idList);
    }

    public boolean isSuperAdmin() {
        // 这里是我自己定义了一个假的超级管理员规则，实际中要根据项目进行修改
        // 可以是配置文件获取，可以指定某个用户，也可以指定某个角色
        Manager user = (Manager) RequestHolder.getCurrentUser();
        if (user.getMail().contains("admin")) {
            return true;
        }
        return false;
    }

    public List<Acl> getRoleAclList(Role role) {
        Example example = new Example(RoleAcl.class);
        example.createCriteria().andEqualTo("role_id", role.getId());
        List<RoleAcl> roleAcls = roleAclMapper.selectByExample(example);

        List<Integer> idList = new ArrayList();
        for (RoleAcl roleAcl: roleAcls){
            idList.add(roleAcl.getRole_id());
        }
        return aclMapper.getByIdList(idList);
    }
}
